package dao

import (
	"crypto/md5"
	"fmt"
	"github.com/jinzhu/gorm"
	"go-admin/global"
	"go-admin/internal/model"
	mr "go-admin/internal/model/api/model_request"
	_const "go-admin/internal/model/const"
	"go-admin/pkg/app"
	"time"
)

func (d *Dao) CreateUser(db *gorm.DB, param *mr.CreateUserRequest) (string, error) {
	user := model.User{
		CommonModel: model.CommonModel{
			Id:    global.GetId(),
			IsDel: _const.ISDEL,
		},
		IsBanned: _const.ISBANNED,
		Username: param.Username,
		Password: fmt.Sprintf("%x", md5.Sum([]byte(param.Password))),
		RealName: param.RealName,
		Phone:    param.Phone,
		Avatar:   param.Avatar,
		Gender:   param.Gender,
		Email:    param.Email,
		DeptId:   param.DeptId,
		JobId:    param.JobId,
	}
	if param.Remark != "" {
		user.Remark = param.Remark
	}
	return user.Create(db)
}
func (d *Dao) GetUserByUserName(username string) (*model.User, error) {
	user := model.User{}
	return user.GetUserByUserName(d.Engine, username)
}

// 查询总数
func (d *Dao) CountUser(param *mr.ListUserRequest) (int, error) {
	user := model.User{
		IsBanned: param.IsBanned,
		DeptId:   param.DeptId,
	}
	return user.Count(d.Engine)
}

// 获取列表
func (d *Dao) GetUserList(param *mr.ListUserRequest, pageIndex, pageSize int) ([]*model.User, error) {
	user := model.User{
		IsBanned: param.IsBanned,
		DeptId:   param.DeptId,
	}
	pageOffset := app.GetPageOffset(pageIndex, pageSize)
	return user.List(d.Engine, pageOffset, pageSize)
}

// 根据id获取详情
func (d *Dao) GetUserById(Id string) (*model.User, error) {
	user := model.User{
		CommonModel: model.CommonModel{Id: Id},
	}
	return user.GetUserById(d.Engine)
}

func (d *Dao) UpdateUser(tx *gorm.DB, param *mr.UpdateUserRequest) error {
	user := model.User{
		CommonModel: model.CommonModel{
			Id: param.Id,
		},
	}
	values := map[string]interface{}{
		"is_banned":   param.IsBanned,
		"modified_on": time.Now().Local().Unix(),
		"username":    param.Username,
		"password":    param.Password,
		"real_name":   param.RealName,
		"dept_id":     param.DeptId,
		"job_id":      param.JobId,
	}
	if param.Remark != "" {
		values["remark"] = param.Remark
	}
	if param.Phone != "" {
		values["phone"] = param.Phone
	}
	if param.Avatar != "" {
		values["avatar"] = param.Avatar
	}
	if param.Gender != "" {
		values["gender"] = param.Gender
	}
	if param.Email != "" {
		values["email"] = param.Email
	}
	return user.Update(tx, values)
}

func (d *Dao) DeleteUserS(ids []string) error {
	user := model.User{}
	values := map[string]interface{}{
		"deleted_on": time.Now().Local().Unix(),
		"is_del":     _const.DEL,
	}
	return user.Deletes(d.Engine, ids, values)
}

